{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# BigQuery ML models with feature engineering\n",
    "\n",
    "In this notebook, we will use BigQuery ML to build more sophisticated models for taxifare prediction.\n",
    "\n",
    "This is a continuation of our [first models](../../02_bqml/solution/first_model.ipynb) we created earlier with BigQuery ML but now with more feature engineering.\n",
    "\n",
    "## Learning Objectives\n",
    "1. Create and train a new Linear Regression model with BigQuery ML\n",
    "2. Evaluate and predict with the linear model\n",
    "3. Apply transformations using SQL to prune the taxi cab dataset\n",
    "4. Create a feature cross for day-hour combination using SQL\n",
    "5. Examine ways to reduce model overfitting with regularization\n",
    "6. Create and train a DNN model with BigQuery ML\n",
    "\n",
    "Each learning objective will correspond to a __#TODO__ in this student lab notebook -- try to complete this notebook first and then review the [solution notebook](../solution/feateng_bqml.ipynb). "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash\n",
    "export PROJECT=$(gcloud config list project --format \"value(core.project)\")\n",
    "echo \"Your current GCP Project Name is: \"$PROJECT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "PROJECT = \"your-gcp-project-here\" # REPLACE WITH YOUR PROJECT NAME\n",
    "REGION = \"us-central1\" # REPLACE WITH YOUR BUCKET REGION e.g. us-central1\n",
    "\n",
    "# Do not change these\n",
    "os.environ[\"PROJECT\"] = PROJECT\n",
    "os.environ[\"REGION\"] = REGION\n",
    "os.environ[\"BUCKET\"] = PROJECT # DEFAULT BUCKET WILL BE PROJECT ID\n",
    "\n",
    "if PROJECT == \"your-gcp-project-here\":\n",
    "  print(\"Don't forget to update your PROJECT name! Currently:\", PROJECT)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create a BigQuery Dataset and Google Cloud Storage Bucket\n",
    "\n",
    "A BigQuery dataset is a container for tables, views, and models built with BigQuery ML. Let's create one called __serverlessml__ if we have not already done so in an earlier lab. We'll do the same for a GCS bucket for our project too."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash\n",
    "\n",
    "## Create a BigQuery dataset for serverlessml if it doesn't exist\n",
    "datasetexists=$(bq ls -d | grep -w serverlessml)\n",
    "\n",
    "if [ -n \"$datasetexists\" ]; then\n",
    "    echo -e \"BigQuery dataset already exists, let's not recreate it.\"\n",
    "\n",
    "else\n",
    "    echo \"Creating BigQuery dataset titled: serverlessml\"\n",
    "    \n",
    "    bq --location=US mk --dataset \\\n",
    "        --description 'Taxi Fare' \\\n",
    "        $PROJECT:serverlessml\n",
    "   echo \"\\nHere are your current datasets:\"\n",
    "   bq ls\n",
    "fi    \n",
    "    \n",
    "## Create GCS bucket if it doesn't exist already...\n",
    "exists=$(gcloud storage ls | grep -w gs://${PROJECT}/)\n",
    "\n",
    "if [ -n \"$exists\" ]; then\n",
    "   echo -e \"Bucket exists, let's not recreate it.\"\n",
    "    \n",
    "else\n",
    "   echo \"Creating a new GCS bucket.\"\n",
    "   gcloud storage buckets create --location ${REGION} gs://${PROJECT}\n",
    "   echo \"\\nHere are your current buckets:\"\n",
    "   gcloud storage ls\n",
    "fi"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model 4: With some transformations\n",
    "\n",
    "BigQuery ML automatically scales the inputs. so we don't need to do scaling, but human insight can help.\n",
    "\n",
    "Since we we'll repeat this quite a bit, let's make a dataset with 1 million rows. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "CREATE OR REPLACE TABLE serverlessml.feateng_training_data AS\n",
    "\n",
    "SELECT\n",
    "  (tolls_amount + fare_amount) AS fare_amount,\n",
    "  pickup_datetime,\n",
    "  pickup_longitude AS pickuplon,\n",
    "  pickup_latitude AS pickuplat,\n",
    "  dropoff_longitude AS dropofflon,\n",
    "  dropoff_latitude AS dropofflat,\n",
    "  passenger_count*1.0 AS passengers\n",
    "FROM `nyc-tlc.yellow.trips`\n",
    "# The full dataset has 1+ Billion rows, let's take only 1 out of 1,000 (or 1 Million total)\n",
    "WHERE ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), 1000)) = 1\n",
    "# placeholder for additional filters as part of TODO 3 later"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "# Tip: You can CREATE MODEL IF NOT EXISTS as well\n",
    "CREATE OR REPLACE MODEL serverlessml.model4_feateng\n",
    "TRANSFORM(\n",
    "  * EXCEPT(pickup_datetime)\n",
    "  , ST_Distance(ST_GeogPoint(pickuplon, pickuplat), ST_GeogPoint(dropofflon, dropofflat)) AS euclidean\n",
    "  , CAST(EXTRACT(DAYOFWEEK FROM pickup_datetime) AS STRING) AS dayofweek\n",
    "  , CAST(EXTRACT(HOUR FROM pickup_datetime) AS STRING) AS hourofday\n",
    ")\n",
    "\n",
    "# TODO 1: Specify the BigQuery ML options for a linear model to predict fare amount\n",
    "# OPTIONS()\n",
    "\n",
    "AS\n",
    "\n",
    "SELECT * FROM serverlessml.feateng_training_data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Once the training is done, visit the [BigQuery Cloud Console](https://console.cloud.google.com/bigquery) and look at the model that has been trained. Then, come back to this notebook."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that BigQuery automatically split the data we gave it, and trained on only a part of the data and used the rest for evaluation. We can look at eval statistics on that held-out data:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "SELECT *, SQRT(loss) AS rmse FROM ML.TRAINING_INFO(MODEL serverlessml.model4_feateng)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "# TODO 2: Evaluate and predict with the linear model\n",
    "# Write a SQL query to take the SQRT() of the Mean Squared Error as your loss metric for evaluation\n",
    "# Hint: Use ML.EVALUATE on your newly trained model\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What is the RMSE? Could we do any better? \n",
    "\n",
    "Try re-creating the above feateng_training_data table with additional filters and re-running training and evaluation.\n",
    "\n",
    "### TODO 3: Apply transformations using SQL to prune the taxi cab dataset\n",
    "\n",
    "Now let's reduce the noise in our training dataset by only training on trips with a non-zero distance and fares above $2.50. Additionally, we will apply some geo location boundaries for New York City. Copy the below into your previous feateng_training_data table creation and re-train your model. \n",
    "\n",
    "```sql\n",
    "AND\n",
    "  trip_distance > 0\n",
    "  AND fare_amount >= 2.5\n",
    "  AND pickup_longitude > -78\n",
    "  AND pickup_longitude < -70\n",
    "  AND dropoff_longitude > -78\n",
    "  AND dropoff_longitude < -70\n",
    "  AND pickup_latitude > 37\n",
    "  AND pickup_latitude < 45\n",
    "  AND dropoff_latitude > 37\n",
    "  AND dropoff_latitude < 45\n",
    "  AND passenger_count > 0\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Yippee! We're now below our target of 6 dollars in RMSE.\n",
    "We are now beating our goals, and with just a linear model.  \n",
    "\n",
    "## Making predictions with BigQuery ML\n",
    "\n",
    "This is how the prediction query would look that we saw earlier [heading 1.3 miles uptown](https://www.google.com/maps/dir/'40.742104,-73.982683'/'40.755174,-73.983766'/@40.7481394,-73.993579,15z/data=!3m1!4b1!4m9!4m8!1m3!2m2!1d-73.982683!2d40.742104!1m3!2m2!1d-73.983766!2d40.755174) in New York City."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "SELECT * FROM ML.PREDICT(MODEL serverlessml.model4_feateng, (\n",
    "  SELECT \n",
    "    -73.982683 AS pickuplon,\n",
    "    40.742104 AS pickuplat,\n",
    "    -73.983766 AS dropofflon,\n",
    "    40.755174 AS dropofflat,\n",
    "    3.0 AS passengers,\n",
    "    TIMESTAMP('2019-06-03 04:21:29.769443 UTC') AS pickup_datetime\n",
    "))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Improving the model with feature crosses\n",
    "\n",
    "Let's do a [feature cross](https://developers.google.com/machine-learning/crash-course/feature-crosses/video-lecture) of the day-hour combination instead of using them raw"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "CREATE OR REPLACE MODEL serverlessml.model5_featcross\n",
    "TRANSFORM(\n",
    "  * EXCEPT(pickup_datetime)\n",
    "  , ST_Distance(ST_GeogPoint(pickuplon, pickuplat), ST_GeogPoint(dropofflon, dropofflat)) AS euclidean\n",
    "    \n",
    "  # TODO 4: Create a feature cross for day-hour combination using SQL  \n",
    "  , ML.( # <--- Enter the correct function for a BigQuery ML feature cross ahead of the (\n",
    "      STRUCT(CAST(EXTRACT(DAYOFWEEK FROM pickup_datetime) AS STRING) AS dayofweek,\n",
    "             CAST(EXTRACT(HOUR FROM pickup_datetime) AS STRING) AS hourofday)\n",
    "  ) AS day_hr\n",
    ")\n",
    "OPTIONS(input_label_cols=['fare_amount'], model_type='linear_reg') \n",
    "AS\n",
    "\n",
    "SELECT * FROM serverlessml.feateng_training_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "SELECT *, SQRT(loss) AS rmse FROM ML.TRAINING_INFO(MODEL serverlessml.model5_featcross)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "SELECT SQRT(mean_squared_error) AS rmse FROM ML.EVALUATE(MODEL serverlessml.model5_featcross)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Sometimes (not the case above), the training RMSE is quite reasonable, but the evaluation RMSE is terrible. This is an indication of overfitting.\n",
    "When we do feature crosses, we run into the risk of overfitting (for example, when a particular day-hour combo doesn't have enough taxirides).\n",
    "\n",
    "## Reducing overfitting\n",
    "\n",
    "Let's add [L2 regularization](https://developers.google.com/machine-learning/glossary/#L2_regularization) to help reduce overfitting. Let's set it to 0.1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "CREATE OR REPLACE MODEL serverlessml.model6_featcross_l2\n",
    "TRANSFORM(\n",
    "  * EXCEPT(pickup_datetime)\n",
    "  , ST_Distance(ST_GeogPoint(pickuplon, pickuplat), ST_GeogPoint(dropofflon, dropofflat)) AS euclidean\n",
    "  , ML.FEATURE_CROSS(STRUCT(CAST(EXTRACT(DAYOFWEEK FROM pickup_datetime) AS STRING) AS dayofweek,\n",
    "                            CAST(EXTRACT(HOUR FROM pickup_datetime) AS STRING) AS hourofday)) AS day_hr\n",
    ")\n",
    "# TODO 5: Set the model options for a linear regression model to predict fare amount with 0.1 L2 Regularization\n",
    "# Tip: Refer to the documentation for syntax: \n",
    "# https://cloud.google.com/bigquery-ml/docs/reference/standard-sql/bigqueryml-syntax-create\n",
    "OPTIONS() \n",
    "AS\n",
    "\n",
    "SELECT * FROM serverlessml.feateng_training_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "SELECT SQRT(mean_squared_error) AS rmse FROM ML.EVALUATE(MODEL serverlessml.model6_featcross_l2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "These sorts of experiment would have taken days to do otherwise. We did it in minutes, thanks to BigQuery ML!  The advantage of doing all this in the TRANSFORM is the client code doing the PREDICT doesn't change. Our model improvement is transparent to client code."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "SELECT * FROM ML.PREDICT(MODEL serverlessml.model6_featcross_l2, (\n",
    "  SELECT \n",
    "    -73.982683 AS pickuplon,\n",
    "    40.742104 AS pickuplat,\n",
    "    -73.983766 AS dropofflon,\n",
    "    40.755174 AS dropofflat,\n",
    "    3.0 AS passengers,\n",
    "    TIMESTAMP('2019-06-03 04:21:29.769443 UTC') AS pickup_datetime\n",
    "))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Let's try feature crossing the locations too\n",
    "\n",
    "Because the lat and lon by themselves don't have meaning, but only in conjunction, it may be useful to treat the fields as a pair instead of just using them as numeric values. However, lat and lon are continuous numbers, so we have to discretize them first. That's what ML.BUCKETIZE does.\n",
    "\n",
    "Here are some of the preprocessing functions in BigQuery ML:\n",
    "* ML.FEATURE_CROSS(STRUCT(features))    does a feature cross of all the combinations\n",
    "* ML.POLYNOMIAL_EXPAND(STRUCT(features), degree)    creates x, x^2, x^3, etc.\n",
    "* ML.BUCKETIZE(f, split_points)   where split_points is an array "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "\n",
    "-- BQML chooses the wrong gradient descent strategy here. It will get fixed in (b/141429990)\n",
    "-- But for now, as a workaround, explicitly specify optimize_strategy='BATCH_GRADIENT_DESCENT'\n",
    "\n",
    "CREATE OR REPLACE MODEL serverlessml.model7_geo\n",
    "TRANSFORM(\n",
    "  fare_amount\n",
    "  , ST_Distance(ST_GeogPoint(pickuplon, pickuplat), ST_GeogPoint(dropofflon, dropofflat)) AS euclidean\n",
    "  , ML.FEATURE_CROSS(STRUCT(CAST(EXTRACT(DAYOFWEEK FROM pickup_datetime) AS STRING) AS dayofweek,\n",
    "                            CAST(EXTRACT(HOUR FROM pickup_datetime) AS STRING) AS hourofday), 2) AS day_hr\n",
    "  , CONCAT(\n",
    "     ML.BUCKETIZE(pickuplon, GENERATE_ARRAY(-78, -70, 0.01)),\n",
    "     ML.BUCKETIZE(pickuplat, GENERATE_ARRAY(37, 45, 0.01)),\n",
    "     ML.BUCKETIZE(dropofflon, GENERATE_ARRAY(-78, -70, 0.01)),\n",
    "     ML.BUCKETIZE(dropofflat, GENERATE_ARRAY(37, 45, 0.01))\n",
    "  ) AS pickup_and_dropoff\n",
    ")\n",
    "OPTIONS(input_label_cols=['fare_amount'], model_type='linear_reg', l2_reg=0.1, optimize_strategy='BATCH_GRADIENT_DESCENT') \n",
    "AS\n",
    "\n",
    "SELECT * FROM serverlessml.feateng_training_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "SELECT SQRT(mean_squared_error) AS rmse FROM ML.EVALUATE(MODEL serverlessml.model7_geo)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Yippee!  We're now below our target of 6 dollars in RMSE."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## DNN\n",
    "\n",
    "You could, of course, train a more sophisticated model.  Change \"linear_reg\" above to \"dnn_regressor\" and see if it improves things.\n",
    "\n",
    "__Note: This takes 20 - 25 minutes to run.__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "-- This is alpha and may not work for you.\n",
    "CREATE OR REPLACE MODEL serverlessml.model8_dnn\n",
    "TRANSFORM(\n",
    "  fare_amount\n",
    "  , ST_Distance(ST_GeogPoint(pickuplon, pickuplat), ST_GeogPoint(dropofflon, dropofflat)) AS euclidean\n",
    "  , CONCAT(CAST(EXTRACT(DAYOFWEEK FROM pickup_datetime) AS STRING),\n",
    "           CAST(EXTRACT(HOUR FROM pickup_datetime) AS STRING)) AS day_hr\n",
    "  , CONCAT(\n",
    "     ML.BUCKETIZE(pickuplon, GENERATE_ARRAY(-78, -70, 0.01)),\n",
    "     ML.BUCKETIZE(pickuplat, GENERATE_ARRAY(37, 45, 0.01)),\n",
    "     ML.BUCKETIZE(dropofflon, GENERATE_ARRAY(-78, -70, 0.01)),\n",
    "     ML.BUCKETIZE(dropofflat, GENERATE_ARRAY(37, 45, 0.01))\n",
    "  ) AS pickup_and_dropoff\n",
    ")\n",
    "-- at the time of writing, l2_reg wasn't supported yet.\n",
    "\n",
    "# TODO 6: Create a DNN model (dnn_regressor) with hidden_units [32,8]\n",
    "OPTIONS() \n",
    "AS\n",
    "\n",
    "SELECT * FROM serverlessml.feateng_training_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "SELECT SQRT(mean_squared_error) AS rmse FROM ML.EVALUATE(MODEL serverlessml.model8_dnn)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We really need the L2 reg (recall that we got 4.77 without the feateng). It's time to do [Feature Engineering in Keras](../../06_feateng_keras/labs/taxifare_fc.ipynb)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Copyright 2019 Google Inc.\n",
    "Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at\n",
    "http://www.apache.org/licenses/LICENSE-2.0\n",
    "Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
